package org.unique.support.orm.tx;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.unique.aop.AbstractMethodInterceptor;
import org.unique.aop.annotation.After;
import org.unique.aop.annotation.Before;

/**
 * 事务拦截器
 * @author biezhi
 * @since 1.0
 */
public class TransactionInterceptor extends AbstractMethodInterceptor {

	private Logger logger = LoggerFactory.getLogger(TransactionInterceptor.class);
	
	private TransactionManager transactionManager;
	
	public TransactionInterceptor(DataSource dataSource) {
		this.transactionManager = new TransactionManager(dataSource);
	}
	
	@Override
	@Before(expression = "@org.unique.support.orm.tx.annotation.Transactional")
	public void beforeAdvice() {
		try {
			transactionManager.start();
		} catch (SQLException e) {
			logger.warn("事务开启失败 " + e.getMessage());
		}
	}

	@Override
	@After(expression = "@org.unique.support.orm.tx.annotation.Transactional")
	public void afterAdvice() {
		try {
			transactionManager.commit();
		} catch (SQLException e) {
			logger.warn("事务提交失败 " + e.getMessage());
		}
	}
	
}
